<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
        position: absolute;
        top: 42%;
        left:40%;
        
        }
        input{
            width: 200px;
            height: 30px;
            margin-bottom: 20px;
            box-sizing: border-box;
        }
       .denglu{
        background-color: cornflowerblue;
        color: white;
        border: 0;
       }
    </style>
</head>
<body>
  <div>
    <input type="text" placeholder="手机号/用户名/邮箱" class="shouji"><br>
    <input type="text" placeholder="密码" class="mima"><br>
    <input type="button" value="登录" class="denglu">
  </div>
</body>
</html>
<script>
  
   let lis=document.querySelectorAll('input')
   
        lis[2].onclick = function(){
          
            if( lis[0].value && lis[1].value ){
          
                if(/^\d{4}$/.test(lis[1].value) ){
             
                    ajax('get','https://yantianfeng.com/api/login',{ username:lis[0].value,password: lis[1].value }, function(data){
                        console.log(data);
                        if( data.status == 200 ){
                            console.log('登陆成功');
                        }else{
                            console.log('登陆失败!');
                        }
                    })
                }else{
                    alert('正确的手机号或密码错误')
                }
            }else{
                alert('用户名或密码不能为空!')
            }
        }
        function objToSearchString(obj){
    var str  = ''
    for(var key in obj){
        str += `${key}=${obj[key]}&`;
    }
    return str.slice(0,str.length-1);
}

//封装ajax函数
function ajax( method, url, params , hd ){
    //1.创建请求对象
    var xhr = new XMLHttpRequest()

    //2.配置请求对象
    xhr.open(method, method == 'get' ? url + "?" + objToSearchString(params) : url );

    //3.设置回调函数
    xhr.onreadystatechange = function(){
        if( xhr.readyState == 4 ){
            hd( JSON.parse(xhr.responseText) )
        }
    }

    //4.发送请求
    //先对post请求设置 content-type 请求头
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    xhr.send(  method == 'get' ? null : objToSearchString(params) );
}



</script>